/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Dimensions,
  Platform,
  ActivityIndicator,
  TouchableOpacity,
  TouchableHighlight,
  ScrollView,
  Image,
  ListView,
  Modal,
  TextInput,
} from 'react-native';

import Video from 'react-native-video';
import Icon from 'react-native-vector-icons/Ionicons';
import Request from '../Common/Request';
import Config from '../Common/Config';
import CButton from 'react-native-button';

const {width, height} = Dimensions.get('window')

export default class Detail extends Component {
    constructor(props) {
        super(props)

        this.state = {
            data: this.props.data,

            rate: 1,
            volume: 1,
            muted: false,
            resizeMode: 'contain',
            duration: 0.0,
            currentTime: 0.0,
            controls: false,
            paused: false,

            videoLoaded: false,
            playing: false,
            playingWrong: false,

            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            }),

            loadingTail: false,
            page: 0,
            items: [],
            total: 0,

            modalAnimationType: 'slide',//none slide fade
            modalVisible: false,//模态场景是否可见
            modaltransparent: true,//是否透明显示

            newComment: '',
            isSendComment: false,
        }

        this._onLoadStart = this._onLoadStart.bind(this)
        this._onLoad = this._onLoad.bind(this)
        this._onProgress = this._onProgress.bind(this)
        this._onEnd = this._onEnd.bind(this)
        this._onError = this._onError.bind(this)

        this._backToPage = this._backToPage.bind(this)

        this._renderRow = this._renderRow.bind(this)
        this._replay = this._replay.bind(this)
        this._pause = this._pause.bind(this)
        this._resume = this._resume.bind(this)

        this._renderHeader = this._renderHeader.bind(this)
        this._renderFooter = this._renderFooter.bind(this)
        this._fetchMoreData = this._fetchMoreData.bind(this)

        this._commentViewVisible = this._commentViewVisible.bind(this)
        this._startShow = this._startShow.bind(this)
        this._submitMsg = this._submitMsg.bind(this)
        this._commentMsg = this._commentMsg.bind(this)
        this._commentBtn = this._commentBtn.bind(this)
    }

    componentDidMount() {
        this._fetchData(1)
    }

    componentWillUnmount() {
        this.timer && clearTimeout(this.timer)
    }

    _fetchData(page) {
        Request.get(Config.api.base + Config.api.comment, {
            accessToken: 'kelvin',
            videoId: '1111',
        })
        .then((responseData) => {
            console.log(responseData);
            if (responseData.success) {
                let oldItems = this.state.items.slice()
                let newItems = []
                if (oldItems.length === 0) {
                    newItems = responseData.data
                } else {
                    newItems = oldItems.concat(responseData.data)
                }

                console.log('total: ' + responseData.total);
                console.log('current: ' + responseData.data.length);

                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(newItems),
                    loadingTail: false,
                    total: responseData.total,
                    items: newItems,
                })
            }
        })
        .catch((error) => {
            console.log(error);
            this.setState({
                loadingTail: false,
            })
        })
    }

    // 上拉加载
    _fetchMoreData() {
        if (!this._hasMore() || this.state.loadingTail) {
            return
        }

        this.setState({
            page: this.state.page + 1,
            loadingTail: true,
        })
        this._fetchData(this.state.page)
    }

    _hasMore() {
        if (this.state.total === 0) {
            return true
        }

        return this.state.items.length !== this.state.total
    }

    _renderRow(data) {
        return (
            <View style={styles.commentBox} key={data._id}>
                <Image
                    style={styles.commentorAvatar}
                    source={{uri: data.commentor.avatar}}
                />
                <View style={styles.commentdescBox}>
                    <Text style={styles.commentNickname}>
                        {data.commentor.nickname}
                    </Text>
                    <Text style={styles.commentTitle}>
                        {data.title}
                    </Text>
                </View>
            </View>
        )
    }

    _onLoadStart() {
        console.log('_onLoadStart');
    }

    _onLoad(data) {
        console.log('_onLoad');
        this.setState({duration: data.duration});
    }

    _onProgress(data) {
        if (!this.state.videoLoaded) {
            this.setState({
                videoLoaded: true,
            })
        }

        if (!this.state.playing) {
            this.setState({
                playing: true,
            })
        }

        this.setState({currentTime: data.currentTime});
    }

    _onEnd() {
        console.log('_onEnd');

        this.setState({
            currentTime: this.state.duration,
        })

        if (this.state.playing) {
            this.setState({
                playing: false,
            })
        }
    }

    _onError() {
        console.log('_onError');
        this.setState({
            playingWrong: true
        })
    }

    _backToPage() {
        let {navigator} = this.props
        if (navigator) {
            navigator.pop()
        }
    }

    getCurrentTimePercentage() {
        if (this.state.currentTime > 0) {
          return parseFloat(this.state.currentTime) / parseFloat(this.state.duration);
        } else {
          return 0;
        }
    }

    _replay() {
        this.refs.videoPlayer.seek(0)

        if (Platform.OS === 'android') {
            this._pause()
            this.timer = setTimeout(
                () => {
                    this._resume()
                },
                100
            )
        }
    }

    _pause() {
        this.setState({
            paused: true
        })
    }

    _resume() {
        this.setState({
            paused: false
        })
    }

    _renderHeader() {
        let data = this.state.data

        return (
            <View style={styles.headerBox}>
                <View style={styles.infoBox}>
                    <Image
                        style={styles.avatar}
                        source={{uri: data.author.avatar}}
                    />
                    <View style={styles.descBox}>
                        <Text style={styles.nickname}>
                            {data.author.nickname}
                        </Text>
                        <Text style={styles.videoTitle}>
                            {data.title}
                        </Text>
                    </View>
                </View>
                <View style={styles.inputBox}>
                    <TextInput
                        style={styles.inputComment}
                        placeholder="输入评论"
                        clearButtonMode="always"
                        underlineColorAndroid="transparent"
                        onChangeText={(msg) => this._commentMsg(msg)}
                        keyboardType="default"
                    />
                    <Text style={styles.inputText}
                        onPress={this._commentBtn}>
                        评论
                    </Text>
                </View>
                <View style={styles.inputLine}>
                </View>

            </View>
        )
    }

    _renderFooter() {
        if (!this._hasMore()) {
            return (
                <View style={styles.footerView}>
                    <Text style={styles.footerText}>
                        没有更多数据了...
                    </Text>
                </View>
            )
        }
        if (!this.state.loadingTail) {
            return (
                <View style={styles.footerView}>
                    <Text style={styles.footerText}>
                        上拉加载更多...
                    </Text>
                </View>
            )
        }
        return (
            <View style={styles.footerView}>
                <Text style={styles.footerText}>
                    努力加载中...
                </Text>
                <ActivityIndicator
                />
            </View>
        )
    }

    _commentViewVisible(visible) {
        console.log(visible);
        if (this.state.modalVisible !== visible) {
            this.setState({
                modalVisible: visible
            })
        }
    }

    _startShow() {
        console.log('show modal')
    }

    _commentMsg(msg) {
        this.setState({
            newComment: msg,
        })
    }

    _commentBtn() {
        if (Platform.OS === 'ios') {
            this._commentViewVisible(true)
        } else {
            this._submitMsg()
        }
    }

    _submitMsg() {
        if (!this.state.newComment) {
            alert('评论不能为空')
            return
        }

        if (this.state.isSendComment) {
            alert('正在发送评论, 稍后重试')
            return
        }

        console.log('发送评论中...');
        this.setState({
            isSendComment: true,
        }, () => {
            let body = {
                accessToken: 'kelvin',
                video_id: '12342',
                content: this.state.newComment,
            }

            Request.post(Config.api.base + Config.api.message, body)
            .then((responseData) => {
                if (responseData && responseData.success) {
                    let newItems = this.state.items.slice()
                    newItems = [{
                        _id: '1234',
                        title: this.state.newComment,
                        commentor: {
                            avatar: 'http://dummyimage.com/320x320/1cc74f)',
                            nickname: 'kelvin',
                        }
                    }].concat(newItems)

                    this.setState({
                        items: newItems,
                        dataSource: this.state.dataSource.cloneWithRows(newItems),
                        total: this.state.total + 1,
                        isSendComment: false,
                    })
                    this._commentViewVisible(false)
                } else {
                    this.setState({
                        isSendComment: false,
                    })

                    console.log('发送评论数据失败');
                }
            })
            .catch((error) => {
                console.log(error);

                this.setState({
                    isSendComment: false,
                })
            })
        })
    }

  render() {
      let data = this.state.data

      const flexCompleted = this.getCurrentTimePercentage() * 100;
      const flexRemaining = (1 - this.getCurrentTimePercentage()) * 100;

    return (
      <View style={styles.container}>
        <View style={styles.header}>
            <View style={styles.backBox}>
                <Icon
                    name='ios-arrow-back'
                    size={26}
                    style={styles.backIcon}
                    onPress={this._backToPage}
                />
            <Text style={styles.backText} onPress={this._backToPage}>
                    返回
                </Text>
            </View>
            <Text style={styles.headerTitle}>
                视频详情界面
            </Text>
        </View>
        <View style={styles.videoBox}>
            <Video
                ref="videoPlayer"
                source={{uri: "http://www.reactnative.vip/data/movie.mp4"}}
                style={styles.video}
                rate={this.state.rate}
                paused={this.state.paused}
                volume={this.state.volume}
                muted={this.state.muted}
                resizeMode={this.state.resizeMode}
                controls={this.state.controls}

                onLoadStart={this._onLoadStart}
                onLoad={this._onLoad}
                onProgress={this._onProgress}
                onEnd={this._onEnd}
                onError={this._onError}
            />

            {!this.state.videoLoaded ?
                <ActivityIndicator
                    style={styles.loading}
                    size="large"
                />
                :
                null
            }

            {this.state.videoLoaded && !this.state.playing ?
                <Icon
                    name='ios-play'
                    size={40}
                    style={styles.playIcon}
                    onPress={this._replay}
                />
                :
                null
            }

            {this.state.videoLoaded && this.state.playing ?
                <TouchableOpacity
                    style={styles.pauseArea}
                    onPress={this._pause}
                >
                    {this.state.paused ?
                        <Icon
                            name='ios-play'
                            size={40}
                            style={styles.playIcon}
                            onPress={ this._resume}
                        />
                        :
                        null
                    }
                </TouchableOpacity>
                :
                null
            }

            {this.state.playingWrong ?
                <Text style={styles.playError}>
                    播放出错了
                </Text>
                :
                null
            }
            <View style={styles.progress}>
                <View style={[styles.innerProgressCompleted, {flex: flexCompleted}]} />
                <View style={[styles.innerProgressRemaining, {flex: flexRemaining}]} />
            </View>
        </View>

        <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderRow}
            enableEmptySections={true}
            automaticallyAdjustContentInsets={false}
            renderHeader={this._renderHeader}
            renderFooter={this._renderFooter}
            onEndReached={this._fetchMoreData}
            onEndReachedThreshold={20}
        />
        <Modal
          animationType={this.state.animationType}
          transparent={this.state.transparent}
          visible={this.state.modalVisible}
          onRequestClose={() => { this._commentViewVisible(false) } }
          onShow={this._startShow}
        >
            <View style={styles.modalContainer}>
                <Icon
                    name='ios-close-outline'
                    size={40}
                    style={styles.closeIcon}
                    onPress={ () => this._commentViewVisible(false)}
                />
                <TextInput
                    style={styles.modalInputText}
                    placeholder="输入评论1111"
                    multiline={true}
                    numberOfLines={5}
                    clearButtonMode="always"
                    underlineColorAndroid="transparent"
                    onChangeText={(msg) => this._commentMsg(msg)}
                />
                <CButton style={styles.submitBtn} onPress={this._submitMsg}>
                    发表评论
                </CButton>
            </View>

        </Modal>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  header: {
      width: width,
      height: 64,
      flexDirection: 'row',
      justifyContent: 'center',
      alignItems: 'center',
      borderBottomWidth: 1,
      borderColor: 'rgba(255, 0, 0, 0.2)',
  },
  backBox: {
      position: 'absolute',
      left: 10,
      width: 100,
      flexDirection: 'row',
      alignItems: 'center',
      top: 25,
  },
  backIcon: {
      color: '#999',
      fontSize: 22,
      marginRight: 5,
  },
  backText: {
      color: '#999',
      fontSize: 16,
  },
  headerTitle: {
      marginTop: 10,
      fontSize: 18,
      color: 'black',
      textAlign: 'center',
      width: width - 120,
  },

  videoBox: {
      width: width,
      height: 240,
      backgroundColor: 'gray'
  },
  video: {
      width: width,
      height: 230,
  },
  progress: {
    width: width,
    height: 10,
    flexDirection: 'row',
    borderRadius: 3,
    overflow: 'hidden',
  },
  innerProgressCompleted: {
    height: 10,
    backgroundColor: '#cccccc',
  },
  innerProgressRemaining: {
    height: 10,
    backgroundColor: '#2C2C2C',
  },
  playIcon: {
      position: 'absolute',
      top: 90,
      left: width * 0.5 - 20,
      width: 40,
      height: 40,
      paddingLeft: 12,
      backgroundColor: 'transparent',
      borderWidth: 1,
      borderColor: 'red',
      borderRadius: 20,
      color: '#ed7b66',
  },
  loading: {
      position: 'absolute',
      top: 120,
      left: 0,
      width: width,
      alignSelf: 'center',
  },
  pauseArea: {
      position: 'absolute',
      width: width,
      top: 0,
      left: 0,
      height: 230,
  },
  playError: {
      position: 'absolute',
      width: width,
      top: 130,
      fontSize: 20,
      textAlign: 'center',
      color: 'red',
      backgroundColor: 'transparent',
  },
  scrollView: {
      flex: 1,
  },
  infoBox: {
      flexDirection: 'row',
      width: width,
      justifyContent: 'center',
      marginTop: 50,
  },
  avatar: {
      width: 60,
      height: 60,
      borderRadius: 30,
      marginLeft: 10,
      marginRight: 10,
  },
  descBox: {
      flex: 1,
  },
  nickname: {
      fontSize: 20,
  },
  videoTitle: {
      marginTop: 5,
      fontSize: 16,
      color: '#666',
  },
  commentBox: {
      flexDirection: 'row',
      width: width,
      justifyContent: 'center',
      marginTop: 10,
  },
  commentorAvatar: {
      width: 40,
      height: 40,
      borderRadius: 20,
      marginLeft: 20,
      marginRight: 20,
  },
  commentdescBox: {
      flex: 1,
  },
  commentNickname: {
      fontSize: 18,
      color: 'orange',
  },
  commentTitle: {
      marginTop: 5,
      fontSize: 14,
      color: '#aaa',
  },
  footerView: {
      marginVertical: 20,
      flexDirection: 'row',
      justifyContent: 'center',
  },
  footerText: {
      textAlign: 'center',
      fontSize: 18,
      color: 'red',
      marginRight: 10,
  },
  headerBox: {
      width: width,
  },
  inputBox: {
      flexDirection: 'row',
      alignItems: 'center',
      marginTop: 10,
      height: 40,
  },
  inputText: {
      width: 60,
      fontSize: 18,
      textAlign: 'center',
      color: 'red',
  },
  inputComment: {
      flex: 1,
      marginLeft: 20,
      borderWidth: 1,
      borderColor: '#ccc',
      borderRadius: 4,
  },
  inputLine: {
      marginTop: 5,
      width: width - 40,
      height: 3,
      marginLeft: 20,
      marginRight: 20,
      backgroundColor: '#666',
  },
  modalContainer: {
      marginTop: 20,
      width: width,
  },
  closeIcon: {
      marginTop: 20,
      marginLeft: 20,
      width: 40,
      height: 40,
  },
  modalInputText: {
      width: width - 40,
      height: 50,
      marginLeft: 20,
      marginTop: 30,
      borderWidth: 1,
      borderColor: '#ccc',
      borderRadius: 4,
  },
  submitBtn: {
      marginTop: 30,
      fontSize: 30,
      color: 'gray',
  },
});
